import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ui/api/config.dart';

import 'state.dart';

class SettingLogic extends GetxController {
  final SettingState state = SettingState();

  RxBool switchvalue = false.obs;
  RxString uid = "".obs; // UID共用
  RxList<String> topicView = ['RedEggPrices', 'WhiteEggPrices', 'PinkEggPrices'].obs; // 主题 list数据
  RxString mqttServer = "".obs; // MQTT服务器地址
  RxString mqttPort = "".obs; // MQTT服务器端口
  RxString topic = "".obs; // 弹窗临时存储 订阅主题
  RxBool isNoSave = RxBool(false); // 是否没有保存

  addtopic() {
    // 添加主题
    Get.defaultDialog(
        title: "添加主题",
        titleStyle: const TextStyle(color: Colors.red, fontSize: 20),
        content: TextField(
          onChanged: (v) => topic.value = v,
          decoration: const InputDecoration(labelText: "主题"),
          maxLines: 1,
        ),
        contentPadding: const EdgeInsets.all(10),
        radius: 20,
        textCancel: "取消", //系统
        textConfirm: "添加",
        onCancel: () {
          debugPrint("点击了取消");
        },
        onConfirm: () async {
          Get.back();
          debugPrint("点击了确定");
          topicView.add(topic.value);
        });
  }

  saveconfigjson() async {
    // 保存配置 todo
    Map<String, dynamic> map = {
      "topics": topicView.toList(),
      "uid": uid.value,
      "host": mqttServer.value,
      "port": mqttPort.value,
    };
    String mapstr = jsonEncode(map);
    debugPrint(mapstr);
    config.savedata(mapstr);

    isNoSave.value = false;
  }

  TextEditingController uidController = TextEditingController();

  @override
  void onInit() {
    super.onInit();
    // 有变化 提示记得保存
    everAll([uid, topicView, mqttServer, mqttPort], (b) => isNoSave.value = true);
    once(uid, (_) => uidController.text = uid.value);
  }
}
